//
//  UITextView+Placeholder.m
//  Soha
//
//  Created by 谭飞 on 2018/8/26.
//  Copyright © 2018年 LB. All rights reserved.
//

#import "UITextView+Placeholder.h"
#import <objc/message.h>

static NSString *placeHoldLabelKey = @"placeHoldLabelKey";
static NSString *placeHoldTextKey = @"placeHoldTextKey";
static NSString *placeHoldColorKey = @"placeHoldColorKey";
static NSString *placeHoldFontKey = @"placeHoldFontKey";

@interface UITextView ()

@property (nonatomic, strong) UILabel *placeHolderLabel;

@end

@implementation UITextView (Placeholder)

- (void)setPlaceHolderLabel:(UILabel *)placeHolderLabel {
    objc_setAssociatedObject(self, &placeHoldLabelKey, placeHolderLabel, OBJC_ASSOCIATION_RETAIN);
}

- (UILabel *)placeHolderLabel {
    
    return objc_getAssociatedObject(self, &placeHoldLabelKey);
}

- (void)setPlaceHolderText:(NSString *)placeHolderText {
    if (!self.placeHolderLabel) {
        
        self.placeHolderLabel = [self createPlaceHolderLabel];
    }
    
    self.placeHolderLabel.text = placeHolderText;
    objc_setAssociatedObject(self, &placeHoldTextKey, placeHolderText, OBJC_ASSOCIATION_COPY);
}

- (NSString *)placeHolderText {
    return objc_getAssociatedObject(self, &placeHoldTextKey);
}


- (void)setPlaceHolderColor:(UIColor *)placeHolderColor {
    if (!self.placeHolderLabel) {
        
        self.placeHolderLabel = [self createPlaceHolderLabel];
    }
    
    self.placeHolderLabel.textColor = placeHolderColor;
    objc_setAssociatedObject(self, &placeHoldColorKey, placeHolderColor, OBJC_ASSOCIATION_RETAIN);

}

- (UIColor *)placeHolderColor {
    return objc_getAssociatedObject(self, &placeHoldColorKey);
}


- (void)setPlaceHolderFont:(UIFont *)placeHolderFont {
    
    if (!self.placeHolderLabel) {
        self.placeHolderLabel = [self createPlaceHolderLabel];
    }
    
    self.placeHolderLabel.font = placeHolderFont;
    objc_setAssociatedObject(self, &placeHoldFontKey, placeHolderFont, OBJC_ASSOCIATION_RETAIN);
}

- (UIFont *)placeHolderFont{
    return objc_getAssociatedObject(self, &placeHoldFontKey);
}


- (UILabel *)createPlaceHolderLabel{
    
    UILabel *label = [[UILabel alloc] init];
    label.numberOfLines = 0;
    label.textColor = [UIColor lightGrayColor];
    label.font = self.font;
    [label sizeToFit];
    [self addSubview:label];
    // KVC
    [self setValue:label forKey:@"_placeholderLabel"];
    
    return label;
}

@end
